package cn.xsly.org.service.impl;

import cn.xsly.basic.exception.BusinessException;
import cn.xsly.basic.util.BaiduAuditUtils;
import cn.xsly.basic.util.Md5Utils;
import cn.xsly.basic.util.StrUtils;
import cn.xsly.org.domain.Employee;
import cn.xsly.org.domain.Shop;
import cn.xsly.org.domain.ShopAuditLog;
import cn.xsly.org.domain.ShopDto;
import cn.xsly.org.mapper.EmployeeMapper;
import cn.xsly.org.mapper.ShopAuditLogMapper;
import cn.xsly.org.mapper.ShopMapper;
import cn.xsly.org.service.IShopService;
import cn.xsly.basic.service.impl.BaseServiceImpl;
import cn.xsly.user.domain.Logininfo;
import cn.xsly.user.mapper.LogininfoMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;

/**
 * 业务实现类：
 */

@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private LogininfoMapper logininfoMapper;


    /**
     * 商家入驻逻辑步骤：
     * 一：检验
     * 1.1.每个参数的空值判断
     * 1.2.两次密码不一致校验
     * 1.3.该店铺是否已经被入驻过
     * 二：入驻业务
     * 2.1.保存店铺管理员信息t_employee
     * 2.2.保存店铺信息t_shop
     * 2.2.将店铺的id更新到t_employee中
     */
    @Override
    public void settlement(Shop shop) {
        //一：检验 - 空值校验：前端的js校验容易被禁用，不安全，后端也要做校验
        if (org.apache.commons.lang3.StringUtils.isEmpty(shop.getName())) { //空和空字符串返回true
            throw new BusinessException("提交资料不能为空!!!");
        }

        //校验店铺名称
        if (!BaiduAuditUtils.TextCensor(shop.getName())) {
            throw new BusinessException("店铺名称不合法!!!");
        }
        //校验logo
        if (!StringUtils.isEmpty(shop.getLogo())) {
            if (!BaiduAuditUtils.ImgCensor("http://123.207.27.208" + shop.getLogo())) {
                throw new BusinessException("logo不合法!!!");
            }
        }

        //二：校验 - 当前店铺是否入驻过
        Shop dbShop = shopMapper.findByNameAndAddress(shop);
        if (dbShop != null) {//查到了 = 入驻过
            throw new BusinessException("请勿重复入驻，忘记密码请联系管理员!!!");
        }

        //添加logininfo信息
        Employee admin = shop.getAdmin();
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(admin.getPassword() + salt);
        admin.setSalt(salt);
        admin.setPassword(md5Pwd);

        //添加logininfo信息
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(admin, logininfo);
        logininfo.setType(0);//管理员
        logininfo.setDisable(true);//可以登陆
        logininfoMapper.add(logininfo);

        //三：数据库操作
        //1.保存t_employee员工信息 - 生成自增id
        admin.setLogininfoId(logininfo.getId());
        employeeMapper.add(admin);//只要添加之后，就生成了自增id

        //2.将自增id设置到shop对象，并保存店铺信息 - 生成店铺的自增id
        shop.setAdminId(admin.getId());
        shopMapper.add(shop);

        //3.将店铺的shopid设置到employee对象，修改employee信息
        admin.setShopId(shop.getId()); //admin对象：id，shopId
        employeeMapper.update(admin);

    }

    private Logininfo admin2Logininfo(Employee admin) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(admin, logininfo);
        //设为管理员
        logininfo.setType(0);
        logininfo.setDisable(true);//可以登陆
        return logininfo;
    }


    @Override
    public void auditPass(ShopAuditLog shopAuditLog) throws MessagingException {
        //获取店铺id在根据ID查所有数据
        Shop shop = shopMapper.findById(shopAuditLog.getShopId());
        shop.setState(2);
        shopMapper.update(shop);

        //2.添加审核日志
        shopAuditLog.setState(2);
        //shopAuditLog.setAuditId(325L); //写死的，因为现在没有登录，不知道是哪一个管理员审核的
        shopAuditLogMapper.add(shopAuditLog);

        //3.发送激活邮件 @TODO
        //创建复杂的邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        //设置发送方
        helper.setFrom("599271526@qq.com");
        Employee employee = employeeMapper.findById(shop.getAdminId());
        //设置收件人
        helper.setTo(employee.getEmail());
        //设置主题
        helper.setSubject("店铺激活邮件");
        //设置内容
        helper.setText("<h2>店铺激活邮件<br/><a href='http://localhost:8080/shop/active/"
                + shop.getId() + "'>点击链接激活</a></h2>", true);
        //发送邮件
        javaMailSender.send(mimeMessage);

    }

    @Override
    public void auditReject(ShopAuditLog shopAuditLog) throws MessagingException {
        //1.改状态：1 - 4
        Shop shop = shopMapper.findById(shopAuditLog.getShopId());
        shop.setState(4);
        shopMapper.update(shop);

        //2.添加审核日志
        shopAuditLog.setState(4);
        //shopAuditLog.setAuditId(325L);
        shopAuditLogMapper.add(shopAuditLog);

        //3.发送邮件重新入驻 @TODO
        //创建复杂的邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        //设置发送方
        helper.setFrom("599271526@qq.com");
        Employee employee = employeeMapper.findById(shop.getAdminId());
        //设置收件人
        helper.setTo(employee.getEmail());
        //设置主题
        helper.setSubject("店铺审核失败");
        //设置内容
        helper.setText("<h2>你的店铺审核失败，请重新入驻<br/>" +
                "<a href='http://localhost:8081/#/register'>点击链接重新入驻</a></h2>", true);
        //发送邮件
        javaMailSender.send(mimeMessage);

        //4.删除入驻信息
        employeeMapper.delete(employee.getId());
        shopMapper.delete(shop.getId());
    }

    @Override
    public List<ShopDto> echarts() {
        return shopMapper.echarts();
    }

    @Override
    public void active(Long id) {
        Shop shopId = shopMapper.findById(id);
        shopId.setState(3);
        shopMapper.update(shopId);
    }


}
